package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 去支付生成订单
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
       return ordersService.addOrders(orders);
    }


    @GetMapping("/userPage")
    public R pageOrders(Integer page,Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        ordersService.page(ordersPage);
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> list = orderDetailService.list(qw);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        Map<Object, Object> map = new HashMap<>();
        map.put("total",ordersPage.getTotal());
        map.put("records",ordersDtos);

        return R.success(map);
    }

    @GetMapping("/page")
    public R pageOrder(Integer page, Integer pageSize, Long number, String beginTime,String endTime){


        log.info("{}",endTime);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(number!=null,Orders::getNumber,number);
        if (beginTime!=null && endTime!=null){
            qw.between(Orders::getOrderTime,beginTime,endTime);
//            qw.gt(Orders::getOrderTime,beginTime);
//            qw.lt(Orders::getOrderTime,endTime);
        }
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        ordersService.page(ordersPage,qw);


        return R.success(ordersPage);
    }

    @PutMapping
    public R updateStatus(@RequestBody Orders orders){

        boolean b = ordersService.updateById(orders);

        return b? R.success("修改成功"): R.error("修改失败");
    }
}
